//https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/
//从中序和后序遍历构造二叉树
//给定两个整数数组 inorder 和 postorder ，其中 inorder 是二叉树的中序遍历， postorder 是同一棵树的后序遍历，请你构造并返回这颗 二叉树 。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    typedef vector<int>::iterator ittor;
    typedef vector<int>::reverse_iterator rittor;

    TreeNode* Create(rittor& rit, ittor left, ittor right)
    {
        if(left > right)
            return nullptr;

        TreeNode* root = new TreeNode(*rit);
        ittor mid = left;
        while(*rit != *mid){++mid;}
        ++rit;
        root->right = Create(rit, mid + 1, right);
        root->left = Create(rit, left, mid - 1);
        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if(inorder.empty())
            return nullptr;

        TreeNode* root = new TreeNode(postorder[postorder.size() - 1]);
        auto rit = postorder.rbegin();
        auto in = inorder.begin();
        while(*rit != *in){++in;}
        ++rit;
        root->right = Create(rit, in + 1, inorder.end() - 1);
        root->left = Create(rit, inorder.begin(), in - 1);
        return root;
    }
};